package com.wanxi.user.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wanxi.user.api.UserFeign;
import com.wanxi.user.domain.dto.UserInfoDto;
import com.wanxi.user.domain.entity.UserInfo;
import com.wanxi.user.domain.query.UserQuery;
import com.wanxi.user.domain.result.UserResult;
import com.wanxi.user.mapper.UserInfoMapper;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author:Iny
 * @Data：2021/12/31 10:01
 */
@RestController
@RequestMapping("back/user")
public class UserInfoServiceImpl implements UserFeign {

    @Resource
    private UserInfoMapper userInfoMapper;


    @ApiOperation(value = "后台查询用户信息")
    @GetMapping("findAll")
    public UserResult<List<UserInfo>> findAll(UserQuery userQuery) {
       PageHelper.startPage(userQuery.getPage(),userQuery.getPageSize());
        List<UserInfo> userInfoVoList = userInfoMapper.findAll(userQuery);
        PageInfo<UserInfo> pageInfo = new PageInfo<>(userInfoVoList);
        List<UserInfo> list = pageInfo.getList();
        return UserResult.success(list);
    }

    @ApiOperation(value = "通过id查询用户信息")
    @ApiImplicitParam(name = "userId", value = "购物车id", dataType = "long", required = true)
    @GetMapping("findById")
    public UserResult<UserInfo> findById(long userId) {
        UserInfo userInfo = userInfoMapper.findById((int)userId);
        return UserResult.success(userInfo);
    }

    @ApiOperation(value = "用户注册账号")
    @PostMapping("addUser")
    public UserResult<Integer> addUser(UserInfoDto userInfoDto) {
        UserInfo userInfo = new UserInfo();
        UserInfo userInfoByEmail = userInfoMapper.findUserInfoByEmail(userInfoDto.getEmail());
        if (userInfoByEmail != null) {
            return UserResult.addUserInfoFailed();
        }
        UserInfo userInfoByPhone = userInfoMapper.findUserInfoByPhone(userInfoDto.getPhone());
        if (userInfoByPhone != null) {
            return UserResult.addUserInfoFailed();
        }
        userInfo.setPhone(userInfoDto.getPhone());
        userInfo.setEmail(userInfoDto.getEmail());
        int addUserInfo = userInfoMapper.addUserInfo(userInfoDto);
        if (addUserInfo != 0) {
            return UserResult.success((int)userInfoDto.getId()) ;
        }
        return UserResult.failed();
    }

    @ApiOperation(value = "通过id修改用户信息")
    @PutMapping("updateById")
    public UserResult<Boolean> updateById(UserInfoDto userInfoDto) {
        int updateId = userInfoMapper.updateById(userInfoDto);
        if (updateId > 0) {
            return UserResult.success(updateId > 0);
        }
        return UserResult.failed();
    }

}
